import tkinter as tk
from tkinter import ttk, simpledialog, filedialog, messagebox
import csv
from datetime import datetime

# 创建主窗口
root = tk.Tk()
root.title("To-Do List")

# 创建 Treeview 控件，并指定列名
tree = ttk.Treeview(root, columns=("Priority", "Content", "Begin Time", "End Time"), show="headings")

# 设置每列的标题
tree.heading("Priority", text="Priority")
tree.heading("Content", text="Content")
tree.heading("Begin Time", text="Begin Time")
tree.heading("End Time", text="End Time")

# 设置每列的宽度
tree.column("Priority", width=50)
tree.column("Content", width=100)
tree.column("Begin Time", width=100)
tree.column("End Time", width=100)

# 添加滚动条
vsb = ttk.Scrollbar(root, orient="vertical", command=tree.yview)
hsb = ttk.Scrollbar(root, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

# 将滚动条放置到窗口中
vsb.pack(side='right', fill='y')
hsb.pack(side='bottom', fill='x')

# 将 Treeview 放置到主窗口中
tree.pack(expand=True, fill=tk.BOTH)

# 加载数据
def load_data(file_path):
    with open(file_path, newline='') as file:
        reader = csv.reader(file)
        for row in reader:
            insert_and_color_row(row)

# 保存数据
def save_data():
    file_path = filedialog.asksaveasfilename(defaultextension=".csv")
    if not file_path:
        return
    with open(file_path, 'w', newline='') as file:
        writer = csv.writer(file)
        for child_id in tree.get_children():
            row = tree.item(child_id)['values']
            writer.writerow(row)
    messagebox.showinfo("Info", "Data saved successfully")

# 添加新数据
def add_new_data():
    user_input = simpledialog.askstring("Input", "Please enter some data (Priority, Content, Begin Time, End Time):")
    if user_input:
        try:
            priority, content, begin_time, end_time = user_input.split(',')
            insert_and_color_row([priority, content, begin_time, end_time])
        except ValueError:
            messagebox.showerror("Error", "Invalid input format. Please use: Priority, Content, Begin Time, End Time")

# 插入行并根据时间范围改变颜色
def insert_and_color_row(row):
    item_id = tree.insert('', 'end', values=row)
    priority, content, begin_time, end_time = row

    # 获取当前时间
    now = datetime.now()
    current_time = now.strftime("%H:%M")
    current = datetime.strptime(current_time, "%H:%M")
    Begin = datetime.strptime(begin_time, "%H:%M")
    End = datetime.strptime(end_time, "%H:%M")

    # 根据时间范围设置颜色
    if Begin > current:
        tree.tag_configure('future', background='lightgreen')
        tree.item(item_id, tags=('future',))
    elif End < current:
        tree.tag_configure('past', background='red')
        tree.item(item_id, tags=('past',))
    else:
        tree.tag_configure('current', background='yellow')
        tree.item(item_id, tags=('current',))

# 删除数据
def remove_data():
    selected_indices = tree.selection()
    if selected_indices:
        for index in reversed(selected_indices):
            tree.delete(index)

# 选择事件处理
def on_select(event):
    # 获取选中的行
    selected_item = tree.selection()
    if selected_item:  # 确保有选中的行
        item_id = selected_item[0]  # 通常只会选中一行，所以取第一个
        # 获取选中行的所有数据
        item_data = tree.item(item_id)
        # 提取特定列的数据
        priority = item_data['values'][0]
        content = item_data['values'][1]
        begin_time = item_data['values'][2]
        end_time = item_data['values'][3]

        # 获取当前时间
        now = datetime.now()
        current_time = now.strftime("%H:%M")
        current = datetime.strptime(current_time, "%H:%M")
        Begin = datetime.strptime(begin_time, "%H:%M")
        End = datetime.strptime(end_time, "%H:%M")

        # 根据时间范围设置颜色
        if Begin > current:
            tree.tag_configure('future', background='lightgreen')
            tree.item(item_id, tags=('future',))
        elif End < current:
            tree.tag_configure('past', background='red')
            tree.item(item_id, tags=('past',))
        else:
            tree.tag_configure('current', background='yellow')
            tree.item(item_id, tags=('current',))

# 绑定选择事件
tree.bind('<<TreeviewSelect>>', on_select)

# 加载按钮
load_button = tk.Button(root, text="Load Data", command=lambda: load_data(filedialog.askopenfilename()))
load_button.pack(side=tk.LEFT, padx=5, pady=5)

# 保存按钮
save_button = tk.Button(root, text="Save Data", command=save_data)
save_button.pack(side=tk.RIGHT, padx=5, pady=5)

# 添加按钮
add_button = tk.Button(root, text="Add New Data", command=add_new_data)
add_button.pack(pady=10)

# 删除按钮
remove_button = tk.Button(root, text="Remove Data", command=remove_data)
remove_button.pack()

# 运行主循环
root.mainloop()